package com.castle.fortress.admin.goods.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.castle.fortress.admin.core.constants.GlobalConstants;
import com.castle.fortress.admin.goods.dto.GoodsTagGroupDto;
import com.castle.fortress.admin.goods.entity.GoodsTagEntity;
import com.castle.fortress.admin.goods.entity.GoodsTagGroupEntity;
import com.castle.fortress.admin.goods.service.GoodsTagGroupService;
import com.castle.fortress.admin.goods.service.GoodsTagService;
import com.castle.fortress.admin.utils.ExcelUtils;
import com.castle.fortress.common.entity.DynamicExcelEntity;
import com.castle.fortress.common.entity.RespBody;
import com.castle.fortress.common.exception.BizException;
import com.castle.fortress.common.respcode.GlobalRespCode;
import com.castle.fortress.common.utils.ConvertUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 商品标签分组表 控制器
 *
 * @author 
 * @since 2021-11-23
 */
@Api(tags="商品标签分组表管理控制器")
@Controller
public class GoodsTagGroupController {
    @Autowired
    private GoodsTagGroupService goodsTagGroupService;
    @Autowired
    private GoodsTagService goodsTagService;

    /**
     * 商品标签分组表的分页展示
     * @param goodsTagGroupDto 商品标签分组表实体类
     * @param current 当前页
     * @param size  每页记录数
     * @return
     */
    @ApiOperation("商品标签分组表分页展示")
    @GetMapping("/goods/goodsTagGroup/page")
    @ResponseBody
    @RequiresPermissions("goods:goodsTagGroup:pageList")
    public RespBody<IPage<GoodsTagGroupDto>> pageGoodsTagGroup(GoodsTagGroupDto goodsTagGroupDto, @RequestParam(required = false) Integer current, @RequestParam(required = false)Integer size){
        Integer pageIndex= current==null? GlobalConstants.DEFAULT_PAGE_INDEX:current;
        Integer pageSize= size==null? GlobalConstants.DEFAULT_PAGE_SIZE:size;
        Page<GoodsTagGroupDto> page = new Page(pageIndex, pageSize);
        IPage<GoodsTagGroupDto> pages = goodsTagGroupService.pageGoodsTagGroupExtends(page, goodsTagGroupDto);

        return RespBody.data(pages);
    }

    /**
     * 商品标签分组表的列表展示
     * @return
     */
    @ApiOperation("商品标签分组表列表展示")
    @GetMapping("/goods/goodsTagGroup/list")
    @ResponseBody
    public RespBody<List<GoodsTagGroupDto>> listGoodsTagGroup(@RequestParam Map<String , Object> params){
        List<GoodsTagGroupDto> list = goodsTagGroupService.getDataAndTagsList(params);
        if(list != null && list.size() > 0){
            list.forEach(e->{
                if(StrUtil.isNotEmpty(e.getTags())){
                    e.setTagsList(Arrays.asList(e.getTags().split(",")));
                }
            });
        }
        return RespBody.data(list);
    }

    /**
     * 商品标签分组表保存
     * @param goodsTagGroupDto 商品标签分组表实体类
     * @return
     */
    @ApiOperation("商品标签分组表保存")
    @PostMapping("/goods/goodsTagGroup/save")
    @ResponseBody
    @RequiresPermissions("goods:goodsTagGroup:save")
    public RespBody<String> saveGoodsTagGroup(@RequestBody GoodsTagGroupDto goodsTagGroupDto){
        if(goodsTagGroupDto == null ){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        GoodsTagGroupEntity goodsTagGroupEntity = ConvertUtil.transformObj(goodsTagGroupDto,GoodsTagGroupEntity.class);
        if(goodsTagGroupService.save(goodsTagGroupEntity)){
            // 将标签保存
            List<String> tagsList = goodsTagGroupDto.getTagsList();
            if(tagsList.size() > 0){
                List<GoodsTagEntity> list = new ArrayList<>();
                for(String tag : tagsList){
                    GoodsTagEntity goodsTagEntity = new GoodsTagEntity();
                    goodsTagEntity.setGroupId(goodsTagGroupEntity.getId());
                    goodsTagEntity.setName(tag);
                    list.add(goodsTagEntity);
                }
                goodsTagService.saveBatch(list);
            }
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 商品标签分组表编辑
     * @param goodsTagGroupDto 商品标签分组表实体类
     * @return
     */
    @ApiOperation("商品标签分组表编辑")
    @PostMapping("/goods/goodsTagGroup/edit")
    @ResponseBody
    @RequiresPermissions("goods:goodsTagGroup:edit")
    public RespBody<String> updateGoodsTagGroup(@RequestBody GoodsTagGroupDto goodsTagGroupDto){
        if(goodsTagGroupDto == null || goodsTagGroupDto.getId() == null || goodsTagGroupDto.getId().equals(0L)){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        GoodsTagGroupEntity goodsTagGroupEntity = ConvertUtil.transformObj(goodsTagGroupDto,GoodsTagGroupEntity.class);
        if(goodsTagGroupService.updateById(goodsTagGroupEntity)){
            // 删旧标签 加新标签
            goodsTagService.deleteByGroupId(goodsTagGroupEntity.getId());
            List<String> tagsList = goodsTagGroupDto.getTagsList();
            if(tagsList.size() > 0){
                List<GoodsTagEntity> list = new ArrayList<>();
                for(String tag : tagsList){
                    GoodsTagEntity goodsTagEntity = new GoodsTagEntity();
                    goodsTagEntity.setGroupId(goodsTagGroupEntity.getId());
                    goodsTagEntity.setName(tag);
                    list.add(goodsTagEntity);
                }
                goodsTagService.saveBatch(list);
            }
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 商品标签分组表删除
     * @param id
     * @return
     */
    @ApiOperation("商品标签分组表删除")
    @PostMapping("/goods/goodsTagGroup/delete")
    @ResponseBody
    @RequiresPermissions("goods:goodsTagGroup:delete")
    public RespBody<String> deleteGoodsTagGroup(@RequestParam Long id){
        if(id == null ){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        if(goodsTagGroupService.removeById(id)) {
            // 删除标签
            goodsTagService.deleteByGroupId(id);
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }


    /**
     * 商品标签分组表批量删除
     * @param ids
     * @return
     */
    @ApiOperation("商品标签分组表批量删除")
    @PostMapping("/goods/goodsTagGroup/deleteBatch")
    @ResponseBody
    @RequiresPermissions("goods:goodsTagGroup:deleteBatch")
    public RespBody<String> deleteGoodsTagGroupBatch(@RequestBody List<Long> ids){
        if(ids == null || ids.size()<1){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        if(goodsTagGroupService.removeByIds(ids)) {
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 商品标签分组表详情
     * @param id 商品标签分组表id
     * @return
     */
    @ApiOperation("商品标签分组表详情")
    @GetMapping("/goods/goodsTagGroup/info")
    @ResponseBody
    @RequiresPermissions("goods:goodsTagGroup:info")
    public RespBody<GoodsTagGroupDto> infoGoodsTagGroup(@RequestParam Long id){
        if(id == null){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        GoodsTagGroupDto goodsTagGroupDto =  goodsTagGroupService.getByIdExtends(id);
        if(StrUtil.isNotEmpty(goodsTagGroupDto.getTags())){
            goodsTagGroupDto.setTagsList(Arrays.asList(goodsTagGroupDto.getTags().split(",")));
        }
        return RespBody.data(goodsTagGroupDto);
    }

	/**
     * 动态表头导出 依据展示的字段导出对应报表
     * @param dynamicExcelEntity
     * @param response
     * @throws Exception
     */
	@PostMapping("/goods/goodsTagGroup/exportDynamic")
	@ApiOperation("动态表头导出，依据展示的字段导出对应报表")
	public void exportDynamic(@RequestBody DynamicExcelEntity<GoodsTagGroupDto> dynamicExcelEntity, HttpServletResponse response) throws Exception {
		List<GoodsTagGroupDto> list = goodsTagGroupService.listGoodsTagGroup(dynamicExcelEntity.getDto());
		//字典、枚举、接口、json常量等转义后的列表数据 根据实际情况初始化该对象，null为list数据直接导出
		List<List<Object>> dataList = null;
		/**
        * 根据实际情况初始化dataList,可参照 com.castle.fortress.admin.system.controller.TmpDemoController类中方法：exportDynamic
        */
		ExcelUtils.exportDynamic(response,dynamicExcelEntity.getFileName()+".xlsx",null,list,dynamicExcelEntity.getHeaderList(),dataList);
	}


}
